package com.wd.zhujiedemo.aop;

import com.wd.zhujiedemo.annotation.ParameterAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author wDong
 * @Date 2022/6/21 14:54
 * @Version 1.0
 */
@Component
@Aspect
public class ParmmeterAspect {


    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation(com.wd.zhujiedemo.annotation.ParameterAnnotation)")
    public void parmmeterPoinCut() {
    }

 /*   @Before("parmmeterPoinCut()")
    public void before(JoinPoint joinPoint) {
        //获取logger
        Class clazz = joinPoint.getTarget().getClass();
        Logger logger = LoggerFactory.getLogger(clazz);
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取Method对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取方法上的注解
        ParameterAnnotation parameterAnnotation = method.getAnnotation(ParameterAnnotation.class);
        //请求参数
        String args = Arrays.toString(joinPoint.getArgs());
        if (parameterAnnotation != null) {
            logger.info("【函数】: {}, 【请求参数】: {}", methodName, args);
        }
        System.out.println("=======================");
    }*/


    @Around("parmmeterPoinCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取logger
        Class clazz = joinPoint.getTarget().getClass();
        Logger logger = LoggerFactory.getLogger(clazz);
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取Method对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取方法上的注解
        ParameterAnnotation parameterAnnotation = method.getAnnotation(ParameterAnnotation.class);
        //请求参数
        String args = Arrays.toString(joinPoint.getArgs());
        if (parameterAnnotation != null) {
            logger.info("【函数】: {}, 【请求参数】: {}", methodName, args);
        }
        //函数开始时间
        long start = System.currentTimeMillis();
        //执行函数
        Object obj;
        try {
            obj = joinPoint.proceed();
        } catch (Exception e) {
            logger.info("【函数】: {}, 【发生异常】: {}", methodName, e.getMessage());
            throw e;
        }
        // 函数结束时间
        long end = System.currentTimeMillis();
        // 记录函数返回值
        logger.info("【函数】: {}, 【返回值】: {}", methodName, obj);
        // 记录函数耗时
        logger.info("【函数】: {}, 【耗时】: {} ms", methodName, (end - start));

        return obj;
    }

}
